/*
 @name: custom_follow.js
 @description: 关注的公众号文章
 @require: vus.js Sogou.util.js jQuery.js
 @date: 2015/9/6
 @author: Nero(Nero@Nero-zou.com)
 */
var MATERIAL_SERVER_BASE=window.top.SITE_URL+'/';
var LoginWXB=window.top.LoginWXB;
var Util=window.top.Util;
var timer;
var wxb = window.top.wxb;
var spider = null;

Vue.filter('wx_name', function (array) {
    var result=[];
    for (var i = 0; i < array.length; i++) {
        var obj = array[i];
        if (obj.length) {
            obj = obj[0];
        }
        result.push(obj.name);
    }
    return result.join('，');
});

var vm = new Vue({
    el: '#my-follow',
    data:{
        is_first:false,//是否只显示头条
        date_range:3,//全部公众号时，显示多少天的数据
        loading:false,
        leftKey:'',
        rightTitle:'全部公众号',
        group_id:'all',
        nowAccount:{},//当前在展示哪个公众号
        leftActiveId:-1,
        leftData:[],
        search_data:[],
        article_all:[],
        article_one:[],
        article_header_wx:{},//当前在展示那个 公众号的文章
        page_all:{},
        page_one:{},
        pause: false,
        is_in_all:true,//是否在 全部公众号模式下
        puclic_all:[
            {
                num: ''
            }
        ],
        waitForAccount: false,
        fetchModalStatus:false,//是否显示更新文章的详情modal
        fetchStatus:false,//是否正在更新文章中
        fetchAutoStatus:false,//是否正在 自动更新 文章 中
        fetchAccounts:[],//所有已关注的公众号
        fetchAccountsMap:{},//所有已关注的公众号的信息 -  {'id':{}...}
        fetchResult:[],//所有已关注的公众号
        fetchProcessStatus:{
            done:0,
            error:[],
            total:0,
            nowAccount:{}
        },//更新文章的 进度信息
        sortKey: null

    },
    methods: {
        clickAddMaterial: function(obj, e) {
            var offset=$(e.target).offset();
            offset.left=offset.left+190;
            offset.top=offset.top+90;
            window.top.Material.addMaterialToCart(obj.article_url,offset);
        },
        clickAddMaterialElse:function(obj){
            window.top.Material.addMaterialToElseCart(obj.article_url);
        },
        headerShow: function () {
            this.is_first = !this.is_first;
            this.loadRightAll();
        },
        menuListShow: function (data_i,e) {
            e.stopPropagation();
            data_i.arrow=!data_i.arrow;
            vm.$set("leftActiveId", data_i.group_id);
            if (data_i.gzh_num === 0 || data_i.accounts !== undefined) {
                return;
            }
            LoginWXB.getFollowGroupAccounts(data_i.group_id).then(function (data) {
                if (data.data.length > 0) {
                    var temp = [];
                    for (var i = 0, max = data.data.length; i < max; i++) {
                        var lev2 = data.data[i];
                        temp.push({
                            id: lev2.id,
                            name: lev2.name,
                            avatar: lev2.avatar,
                            desc: lev2.desc,
                            group: lev2.group,
                            is_verify: lev2.is_verify,
                            qrcode: lev2.qrcode,
                            update_time: lev2.update_time,
                            weixin_id: lev2.weixin_id
                        });
                    }
                    data_i.$set('accounts', temp);
                }
            }).catch(function (e) {
                toastr.error(e,"加载公众号失败");
            });

        },
        showAll: function () {
            this.nowAccount={};
            this.group_id="all";
            this.rightTitle='全部公众号';
            $("#list_search").hide();
            $("#list_menu").show();
            $("#resultNO").hide();
            this.leftKey = '';
            this.is_in_all = true;
            this.loadRightAll();
        },
        showGroupArticle: function (obj) {
            obj.open=!obj.open;
            this.nowAccount={};
            this.group_id=obj.group_id;
            this.rightTitle=obj.group_name;
            $("#list_search").hide();
            $("#list_menu").show();
            $("#resultNO").hide();
            this.leftKey = '';
            this.is_in_all = true;
            this.loadRightAll();
        },
        showOneArticle: function (obj) {
            this.nowAccount=obj;
            this.is_in_all = false;
            this.loadRightOne({id:obj.id,name:obj.name});
        },
        searchPublicNum: function (key) {
            console.log(key);
        },
        searchPublicNumHide: function () {
            $("#list_search").hide();
            $("#list_menu").show();
            $("#resultNO").hide();
            this.leftKey = '';
        },
        latelyTime: function (day) {
            this.date_range=day;
            this.loadRightAll();
        },
        sortAll: function(sortKey){
            this.sortKey = sortKey || null;
            this.loadRightAll();
        },
        sortOne: function(sortKey){
            this.sortKey = sortKey || null;
            this.loadRightOne();
        },
        /**
         * 加载全部公众号的文章
         * @param config
         * @param [append]
         */
        loadRightAll: function (config,append) {
            var _this = this;
            var article_all = [];
            var defaultConfig = {
                page: 1,
                is_first: this.is_first ? 1 : 0,
                days: this.date_range
            };
            _this.loading = true;
            if (append) {
                article_all = this.article_all;
            }
            config = $.extend(true, {}, defaultConfig, config);

            var pars = {
                page: config.page,
                is_first: config.is_first,
                days: config.days,
                group_id:_this.group_id==="all"?undefined:_this.group_id
            };
            if (_this.sortKey) {
                pars.order = _this.sortKey;
            }
            LoginWXB.getFollowAccountsArticle(pars).then(function (data) {
                console.log('--1::::::::::::::::::::::::', data);
                _this.loading=false;
                for (var i = 0, max = data.data.length; i < max; i++) {
                    var obj=data.data[i];
                    article_all.push(obj);
                }
                _this.article_all=article_all;
                _this.page_all=data.pager;
            }).catch(function (e) {
                _this.loading=false;
                toastr.error(e,"加载文章失败");
            });

        },
        /**
         * 加载单个公众号的文章
         */
        loadRightOne:function(config,append){
            if(config && config.name){
                this.rightTitle= config.name;
            }
            var _this=this;
            var article_one = [];
            var defaultConfig = {
                page: 1,
                id: config.id
            };
            _this.loading=true;
            if(append){
                article_one=this.article_one;
            }
            config = $.extend(true, {}, defaultConfig, config);
            config.gzh_id=config.id;
            if (_this.sortKey) {
                config.sort = _this.sortKey;
            }
            LoginWXB.getFollowAccountArticle(config).then(function (data) {
                _this.loading=false;
                for (var i in data.data) {
                    if(data.data.hasOwnProperty(i)){
                        for (var j = 0, max = data.data[i].length; j < max; j++) {

                            var data_name = i;
                            data_name = data_name.split("_");
                            data_name = data_name[0].split("-")[1] + "月" + data_name[0].split("-")[2] + "日";
                            article_one.push({
                                article_time: data_name,
                                is_original: data.data[i][j].is_original,
                                article_title: data.data[i][j].article_title,
                                article_url: data.data[i][j].article_url,
                                content_type: data.data[i][j].content_type,
                                id: data.data[i][j].id,
                                idx: data.data[i][j].idx,
                                like_num: data.data[i][j].like_num,
                                publish_time: data.data[i][j].publish_time,
                                read_num: data.data[i][j].read_num,
                                update_time: data.data[i][j].update_time,
                                article_text: i

                            });
                        }
                    }
                }
                _this.article_one=article_one;
                _this.article_header_wx=data.gzh_info;
                _this.page_one=data.pager;
            }).catch(function (e) {
                _this.loading=false;
                toastr.error(e,"加载文章失败");
            });
        },
        loadMoreall: function () {
            var $num = parseInt(this.page_all.page);
            this.loadRightAll({page:++$num},true);
        },
        loadMoreOne: function () {
            var accountInfo=this.nowAccount;
            var pager=this.page_one;
            var nowPage=parseInt(pager.page);
            var config={
                id:accountInfo.id,
                name:accountInfo.name,
                page: ++nowPage
            };
            this.loadRightOne(config,true);

        },

        openByOuter:function(href){
            window.top.openUrlToBrowser(href);
        },
        followList:function(){
            var url=MATERIAL_SERVER_BASE+'home#!/follow/index?showAdd=1';
            window.top.GUI.Window.open(url, {
                position: 'center',
                height:600,
                width:1120,
                "title": "微小宝客户端",
                "icon": "assest/img/icon.png",
                "toolbar": true,
                "frame": true
            });
        },
        refreshPage:function(){
            window.location.reload();
        },
        /**
         * 获取我关注的公众号列表
         */
        getFetchAccounts:function(){
            var _this=this;
            LoginWXB.getFollowAccounts().then(function (response) {
                console.log('accounts::::', response.data);
                _this.fetchAccounts=response.data;
                _this.fetchAccountsMap={};
                for (var i = 0; i < response.data.length; i++) {
                    var obj = response.data[i];
                    obj.wx_id=obj.wx_account;
                    _this.fetchAccountsMap[obj.id]=obj;
                }
            }).catch(function () {
                //toastr.error(err,"");
            });

        },
        /**
         * 开始更新文章
         * @param type - 是否强制更新全部
         */
        startFetch:function(type){
            var _this=this;
            // var accounts=[];
            //
            // if(type==='auto' || _this.is_in_all){
            //     for (var i = 0; i < _this.fetchAccounts.length; i++) {
            //         var obj = _this.fetchAccounts[i];
            //         accounts.push(obj);
            //     }
            //     if(type!=='auto' && accounts.length===0){
            //         toastr.error("","没有需要更新的文章");//只有 手动触发 才弹出提示
            //         return ;
            //     }
            // }else{
            //     var nowAccountId=_this.nowAccount.id;
            //     var nowAccount=_this.fetchAccountsMap[nowAccountId];
            //     accounts=[nowAccount];
            // }
            //
            // if(type==='auto'){
            //     _this.fetchAutoStatus=true;
            // }
            if (_this.statusInterval) {
                clearInterval(_this.statusInterval);
            }
            _this.fetchStatus=true;
            _this.waitForAccount = true;
            _this.fetchProcessStatus.done=0;
            _this.fetchProcessStatus.error=[];
            _this.fetchProcessStatus.total= 0;
            _this.fetchProcessStatus.nowAccount = {};

            function _updateStatus(status, done) {
                _this.fetchProcessStatus.done = status.allTasksNum - status.failure.length - status.tasks.length - 1;
                if (_this.fetchProcessStatus.done < 0) {
                    _this.fetchProcessStatus.done = 0;
                }
                _this.fetchProcessStatus.error= status.failure;
                _this.fetchProcessStatus.total = status.allTasksNum;
                _this.fetchProcessStatus.nowAccount = status.currentTask;
                if (done) {
                    _this.fetchProcessStatus.done = _this.fetchProcessStatus.total - _this.fetchProcessStatus.error.length;
                }
            }

            spider = new Spider(window.atob, {
                callback: {
                    onTaskStart: function(){
                        _this.waitForAccount = false;
                        _updateStatus(spider.getStatus());
                    },
                    onTaskComplete: function(){
                        _updateStatus(spider.getStatus());
                    },
                    onTaskFailure: function(task){
                        _updateStatus(spider.getStatus());
                        try {
                            LoginWXB.reportFailedAccount([task]);
                        }catch(e){
                            console.log();
                        }
                    },
                    onDone: function(){
                        _updateStatus(spider.getStatus(), 'done');
                    },
                    onVerify: function(url){
                        // _this.pause = true;
                        // window.open(url);
                    }
                },
                verifyFrame: document.getElementById('verifyFrame')
            });

            LoginWXB.getfollowedAccountName().then(function(res){
                var taskData = res.data;
                var nowAccountId = _this.nowAccount.id;
                if (nowAccountId) {
                    var nowAccount= _this.fetchAccountsMap[nowAccountId];
                    taskData = taskData.filter(function(item) {
                        return item.name === nowAccount.wx_name;
                    });
                }
                console.log('task list:', taskData);
                spider.start(taskData);
            });
        },
        /**
         * 获取公众号的最新信息
         * @param account
         * @param callback
         */
        getAccountLatestInfo:function(account,callback){
            var _this=this;
            if(!account.crawl_url || account.crawl_url.match(/^http[s]:\/\/mp.weixin.qq.com/)===null){
                if(callback){
                    callback(account);
                }
                return;
            }
            Sogou.getAccountInfo(account.crawl_url).then(function (newInfo) {
                //公众的 名字或者微信号 改了
                if(account.wx_name!==newInfo.wx_name || account.wx_id!==newInfo.wx_id){
                    account.wx_name=newInfo.wx_name;
                    account.wx_id=newInfo.wx_id;
                    _this.updateAccount(account);
                }
                if(callback){
                    callback(account);
                }
            }).catch(function () {
                if(callback){
                    callback(account);
                }
            });
        },
        /**
         * 更新账号的信息
         * @param account
         */
        updateAccount:function(account){
            var _this=this;
            var saveUrl=MATERIAL_SERVER_BASE+'client/updateaccount';
            _this.fetchAccountsMap[account.id]=account;
            for (var i = 0; i < _this.fetchAccounts.length; i++) {
                var obj = _this.fetchAccounts[i];
                if(obj.id===account.id){
                    obj.wx_name=account.wx_name;
                    obj.wx_id=account.wx_id;
                }
            }
            for (var j = 0; j < _this.leftData.length; j++) {
                var obj1 = _this.leftData[j];
                for (var k = 0; k < obj1.accounts.length; k++) {
                    var obj2 = obj1.accounts[k];
                    if(obj2.id===account.id){
                        obj2.name=account.wx_name;
                        obj2.weixin_id=account.wx_id;
                    }
                }
            }
            $.post(saveUrl,{account_id:account.id,wx_name:account.wx_name,wx_id:account.wx_id},function(){

            },'json');
        },

        postFetchResult:function(data){
            var saveUrl=MATERIAL_SERVER_BASE+'client/saveback';
            $.post(saveUrl,{t:'following',d:data},function(){
                //console.log(response);
            },'json');
        },

        refreshRight:function(){
            var _this=this;
            if(this.is_in_all){
                this.loadRightAll();
            }else{
                this.loadRightOne({id:_this.nowAccount.id});
            }
        },
        fetchDone:function(){
            this.fetchModalStatus=false;
            if(this.isFetchDone()){
                this.fetchStatus=false;
                this.refreshRight();
            }
        },
        isFetchDone:function(){
            return this.fetchProcessStatus.done+this.fetchProcessStatus.error.length>=this.fetchProcessStatus.total;
        },
        autoFetch:function(){
            var _this=this;
            if(this.fetchStatus || this.fetchAutoStatus ||this.fetchModalStatus){
                return;
            }

            _this.startFetch('auto');
        },
        restart: function(){
            this.pause = false;
            spider.reStart();
        }
    }

});

vm.$watch('leftKey', function (newVal) {

    var $search_data = [];
    var $key = newVal;

    if ($key.length > 0) {

        clearTimeout(timer);

        $("#list_search").show();
        $("#list_menu").hide();
        $(".del").show();
        //$("#resultNO").hide();
        timer = setTimeout(function () {
            $.get(MATERIAL_SERVER_BASE + 'follow/accounts', {
                kw: $key
            }, function (data) {

                data = $.parseJSON(data);

                if (data.length < 1) {

                    $("#list_search").hide();
                    $("#resultNO").show();
                }
                else {
                    for (var i = 0, max = data.length; i < max; i++) {
                        $search_data.push({
                            avatar: data[i].avatar,
                            id: data[i].id,
                            name: data[i].name
                        });
                    }

                    vm.$set("search_data", $search_data);

                    $("#list_search").show();
                    $("#resultNO").hide();

                }
            });

        }, 300);

    }
});


function init() {
    page_layout();

    var layoutLeft=$('.layout-left');
    var myFollow=$('#my-follow');
    setInterval(function () {
        layoutLeft.height(myFollow.height()-5);
    },500);

    if(!window.top.wxb.hasLogin){
        toastr.error("","请先登录");
        return;
    }
    setInterval(vm.autoFetch,15*60*1000);//每15分钟 自动更新公众号文章
    var $scope = vm.$data.leftData;
    vm.getFetchAccounts();
    LoginWXB.getFollowGroupsAccounts().then(function (response) {
        var data=response.data;
        var $puclic_all = vm.$data.puclic_all;
        $puclic_all[0].num = 0;
        for (var i = 0, max = data.length; i < max; i++) {
            $scope.push({
                group_id: data[i].group_id,
                group_name: data[i].group_name,
                gzh_num: data[i].gzh_num,
                open: false,
                arrow: false
            });
            $puclic_all[0].num = $puclic_all[0].num + parseInt($scope[i].gzh_num);
            if (i === 0) {
                $scope[0].open = false;
            }
            if (data[i].accounts) {

                $scope[i].accounts = [];

                for (var j = 0, inmax = data[i].accounts.length; j < inmax; j++) {
                    $scope[i].accounts.push({
                        avatar: data[i].accounts[j].avatar,
                        desc: data[i].accounts[j].desc,
                        group: data[i].accounts[j].group,
                        id: data[i].accounts[j].id,
                        is_verify: data[i].accounts[j].is_verify,
                        name: data[i].accounts[j].name,
                        qrcode: data[i].accounts[j].qrcode,
                        update_time: data[i].accounts[j].update_time,
                        weixin_id: data[i].accounts[j].weixin_id
                    });
                }

            }

        }
        vm.$set("puclic_all", $puclic_all);
        vm.$set("leftData", $scope);
        $(".js-menu-list-all").show();
    }).catch(function (e) {
        toastr.error(e,"加载关注的公众号失败");
    });

    vm.loadRightAll();
}

$(window).resize(function(){
    page_layout();
});
function page_layout(){
    var winHeight=$(window).height();
    $('#list_menu').height(winHeight-140);
}
